package com.geline.cloud.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import com.geline.sdk.core.BaseSessionService;
import com.geline.sdk.exception.NotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 描述
 *
 * @author: mx
 * @date: 2024-06-07 15:29
 */
@Component
@Slf4j
public class MyBaseSessionService implements BaseSessionService<Long> {

    @Override
    public void checkLogin() {
        getSSOToken(true);
    }

    @Override
    public Long getUserId() {
        SSOToken ssoToken = getSSOToken(true);
        return Long.valueOf(ssoToken.getId());
    }

    @Override
    public Long getUserIdNotHandle() {
        SSOToken ssoToken = getSSOToken(false);
        if(ssoToken != null){
            return Long.valueOf(ssoToken.getId());
        }else {
            return null;
        }
    }

    @Override
    public String getUserName() {
        SSOToken ssoToken = getSSOToken(false);
        if(ssoToken != null){
            return ssoToken.getIssuer();
        }else {
            return null;
        }
    }

    @Override
    public String getTenantId() {
        SSOToken ssoToken = getSSOToken(false);
        if(ssoToken != null){
            return ssoToken.getTenantId();
        }else {
            return null;
        }
    }

    @Override
    public String login(Object userId, String loginName, String userName, String tenantId) {
        String issuer = StrUtil.isNotBlank(userName) ? userName : loginName;
        //创建一个token
        SSOToken ssoToken = new SSOToken().setId(userId).setIssuer(issuer);
        ssoToken.setTenantId(tenantId==null ? "" : tenantId);
        SSOHelper.setCookie(getRequest(), getResponse(), ssoToken);
        return ssoToken.getToken();
    }

    public static SSOToken getSSOToken(boolean checked) {
        SSOToken ssoToken = null;
        try {
            ssoToken = SSOHelper.getSSOToken(getRequest());
            if(Objects.isNull(ssoToken)){
                String accessToken = getRequest().getHeader("Accesstoken");
                ssoToken = SSOToken.parser(accessToken, false);
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        if(ssoToken == null){
            if(checked){
                throw new NotLoginException("未登录(Null-Token)");
            }else {
                return null;
            }
        }
        long createAt = ssoToken.getTime();
        long currTime = System.currentTimeMillis();
        //过期秒数
        int maxAge = SSOHelper.getSsoConfig().getCookieMaxAge();
        long curr = currTime - createAt;
        if(curr > maxAge*1000){
            if(checked){
                throw new NotLoginException("未登录(token timeout)!");
            }else {
                return null;
            }
        }
        return ssoToken;
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }
}
